local userId = KEYS[1]
local userId_2 = KEYS[2]
local shopId = KEYS[3]
local shopId_2 = KEYS[3]

local orderId = ARGV[1]
local aliveTimes = tonumber(ARGV[2])
local aliveSeconds = ARGV[3]
local orderJsonStr = ARGV[4]

local currRawValue = tonumber(redis.call('get', userId) or '0')
local usedStockValue = tonumber(redis.call('get', shopId) or '0')
local maxStockValue = 5
-- local maxStockValue = tonumber(redis.call('get', shopId_2) or '0')
if currRawValue < 1 then
    if usedStockValue < maxStockValue then
        redis.call('incrby', userId, 1)
        redis.call('expire', userId, aliveSeconds)
        redis.call('hset', userId_2, orderId, orderJsonStr)
        redis.call('incrby', shopId, 1)
        return 1
    else
        return 0
    end
elseif currRawValue >= aliveTimes then
    return 0
else
    if usedStockValue < maxStockValue then
        redis.call('incrby', userId, 1)
        redis.call('hset', userId_2, orderId, orderJsonStr)
        redis.call('incrby', shopId, 1)
        return 1
    else
        return 0
    end
end